﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JCPogi.Core;
using JCPogi.Core.Helpers;

namespace JCPogi.Client {
    public partial class SendSmsProgressForm : Form {

        public SendSmsProgressForm() {
            InitializeComponent();
        }

        public SendSmsProgressForm(DeviceCommandContext commandContext) : this() {
            _commandContext = commandContext;
        }

        private void SendSmsProgressForm_Load(object sender, EventArgs e) {
            _commandContext.PerformCommandAsync(OnSendSmsComplete, OnPublishUpdate);
        }

        private void btnAction_Click(object sender, EventArgs e) {
            switch (btnAction.Text) {
                case TERMINATEBUTTON_TEXT:
                    _commandContext.StopAsyncCommand();
                    btnAction.Text = CLOSEBUTTON_TEXT;
                    doneWaitingLabel.Text = DONEWAITING_TEXT;
                    progressBar.Hide();
                    break;
                case CLOSEBUTTON_TEXT:
                    Close();
                    break;
                default:
                    throw new InvalidOperationException("Unknown action: {0}".WithTokens(btnAction.Text));
            }
        }

        private void OnSendSmsComplete(DeviceCommandResult result) {
            btnAction.Text = CLOSEBUTTON_TEXT;
            doneWaitingLabel.Text = DONEWAITING_TEXT;
            progressBar.Hide();

            if (!result.IsSuccessful) {
                MessageBox.Show("Bulk message sending failed. Reason: {0}".WithTokens(result.ErrorMessage).Ellipsify(255), "Send SMS Failed.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else {
                MessageBox.Show("Bulk message sending completed successfully.", "Send SMS Successful.", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            _commandContext.Dispose();
            _commandContext = null;
        }

        private void OnPublishUpdate(string message) {
            //TODO: show the message somewhere...
            activityLogs.BeginInvoke(new InvokeDelegate(() => {
                activityLogs.Text = activityLogs.Text + "{0}\r\n".WithTokens(message);
            }));
        }

        delegate void InvokeDelegate();
        private DeviceCommandContext _commandContext;
        const string TERMINATEBUTTON_TEXT = "Cancel";
        const string CLOSEBUTTON_TEXT = "Close";
        const string DONEWAITING_TEXT = "Done.";
    }
}
